package com.six.advice;

import com.six.interceptor.AdminThreadLocal;
import com.six.permission.Permission;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class PermissionAdvice {
    @Pointcut("execution(* com.six.controller.*Controller.*(..)))")
    public void pointCut() {}

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature= (MethodSignature) signature;

        Method method = methodSignature.getMethod();
        Permission methodAnnotation = method.getAnnotation(Permission.class);
        if(methodAnnotation != null) {
            String perm = methodAnnotation.value();

            String perms = AdminThreadLocal.getAdminDto().getPerms();

            String[] permArray = perms.split(",");

            for (String tag:permArray) {
                if (tag.equals(perm)) return joinPoint.proceed();
            }
        }
        // 没有权限注解 直接放行
        return joinPoint.proceed();
    }
}
